package com.quectel.business.dms.device;

import com.quectel.business.dms.AccessorUtils;
import com.quectel.business.dms.application.access.Accessor;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.device.dto.DeviceCommandTemplateDto;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.dto.DeviceTypeDto;
import com.quectel.core.module.device.dto.mongo.MongoDeviceCommandLogDto;
import com.quectel.core.module.device.service.DeviceCommandTemplateService;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.device.service.DeviceTypeService;
import com.quectel.core.module.device.service.mongo.MongoDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @author rananxin
 * @date 2021/11/29 5:14 下午
 */
@Component
@Slf4j
public class CommandBusiness {

    @DubboReference
    private DeviceService deviceService;
    @DubboReference
    private DeviceCommandTemplateService deviceCommandTemplateService;
    @DubboReference
    private DeviceTypeService deviceTypeService;
    @DubboReference
    private MongoDeviceService mongoDeviceService;

    public void send(Long deviceId, Long commandTemplateId, Map<String, Object> params
            , MongoDeviceCommandLogDto.OperatorTypeEnum operatorTypeEnum, Long operateId) throws Exception {

        DeviceDto deviceDto = deviceService.selectById(deviceId);
        DeviceCommandTemplateDto deviceCommandTemplateDto = deviceCommandTemplateService.selectById(commandTemplateId);
        if (deviceDto == null || deviceCommandTemplateDto == null) {
            throw new IllegalArgumentException();
        }

        DeviceTypeDto deviceTypeDto = deviceTypeService.selectById(deviceDto.getDeviceTypeId());

        Accessor accessor = AccessorUtils.getBaseAccessor(deviceTypeDto);

        // 路由到具体位置下发

        MongoDeviceCommandLogDto commandLogDto = MongoDeviceCommandLogDto.builder()
                .deviceDto(deviceDto)
                .deviceCommandTemplateDto(deviceCommandTemplateDto)
                .sendOriginalMsg(params)
                .sendTime(new Date())
                .sendStatus(SystemConstants.FAIL)
                .operatorId(operateId)
                .operatorType(operatorTypeEnum.getOperatorType()).build();

        Long cId = mongoDeviceService.saveCommandData(commandLogDto);

        accessor.sendCmd(deviceDto, deviceCommandTemplateDto, params, cId);
        // 下发后根据cId更新 sendParsedMsg sendTime sendStatus

    }
}
